package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.bean.BuyerBean;
import com.project.bean.BuyerCarBean;
import com.project.mapper.*;
import com.project.service.IBuyerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;

@Service
public class BuyerServiceImpl implements IBuyerService {
    @Autowired
    private IBuyerMapper buyerMapper;
    @Autowired
    private IBuyerCarMapper buyerCarMapper;
    @Autowired
    private IBuyerInfoMapper buyerInfoMapper;
    @Autowired
    private IProductMapper productMapper;
    @Autowired
    private ISupplierMapper supplierMapper;

    /**
     * 1、完成采购信息的添加
     * 2、根据登录用户的编号查询采购车的集合
     * 3、根据采购车的集合添加采购明细，同时修改库存商品的最新采购价格和库存数量进行累加
     * 4、采购订单添加成功后，清空该用户的采购车信息
     *
     * @param buyer  采购对象
     * @param userId 采购员编号
     */
    @Override
    public void add(BuyerBean buyer, Integer userId) {
        buyerMapper.insert(buyer);
        System.out.println(buyer);
        System.out.println(userId);

        QueryWrapper<BuyerCarBean> qw = new QueryWrapper<>();
        qw.eq("fk_userId", userId);
        List<BuyerCarBean> buyerCarList = buyerCarMapper.selectList(qw);
        System.out.println(buyerCarList);
        buyerInfoMapper.addBuyerInfo(buyer.getId(), buyerCarList);
        productMapper.updateBuyerInfo(buyerCarList);

        buyerCarMapper.delete(qw);
    }

    /**
     * 动态分页查询
     *
     * @param pageNo    页码
     * @param name      供应商名称
     * @param startDate 采购开始日期
     * @param endDate   采购结束日期
     * @return 分页对象
     */
    @Override
    public IPage<BuyerBean> findByItem(Integer pageNo, String name, LocalDate startDate, LocalDate endDate) {
        return buyerMapper.findByItem(new Page<>(pageNo, 3), name, startDate, endDate);
    }

    /**
     * 按采购id查询 并查询该采购明细的信息，同时查询供应商名称，并查询该购物明细，在采购明细中，需要查询采购商品信息，
     *
     * @param id 采购编号
     * @return 采购对象
     */
    @Override
    public BuyerBean findById(Integer id) {
//        QueryWrapper<BuyerBean> qw = new QueryWrapper<>();
//        qw.eq("pk_buyerId",id);
//        BuyerBean buyer = buyerMapper.selectOne(qw);
//        buyer.setSupplier(supplierMapper.findSup(id));
//        buyer.setProduct(buyerInfoMapper.findInfo(id));
//        return buyer;

        BuyerBean buyerBean = buyerMapper.selectById(id);
        buyerBean.setProduct(buyerInfoMapper.findList(id));
        buyerBean.setSupplier(supplierMapper.findByBuyerId(id));
        return buyerBean;
    }
}
